<template>
  <div>
    <BreakSpace label="客户信息" :containerStyle="{ marginBottom: '10px' }"/>
    <FilterTable ref="table"
      :columns="customerColumns"
      :dataSource="customerList"
      :isSelectColumn="false"
      :isToperInfo="false"
      :height="'auto'"
      columnsRef="ysjSaelsVisitDetail2019092502Table"
      :onColumnsChange="columns => (this.answerColumns = columns)">
    </FilterTable>

    <BreakSpace label="联系人信息" :containerStyle="{ marginBottom: '10px' }"/>
    <FilterTable ref="contactsTable"
      :columns="contactsColumns"
      :dataSource="contactsList"
      :isSelectColumn="false"
      :isToperInfo="false"
      :height="'auto'"
      columnsRef="ysjSaelsVisitDetail2019092503Table"
      :onColumnsChange="columns => (this.answerColumns = columns)">
    </FilterTable>

    <BreakSpace label="关爱信息" :containerStyle="{ marginBottom: '10px' }"/>
    <FormPanel
      ref="formPanel"
      :list="formList"
      :formType="type"
      labelWidth="100"
      :isSubmitBtn="false"
      @formChange="formChangeHandle"
    />

    <BreakSpace label="关爱相关" :containerStyle="{ marginBottom: '10px' }"/>
    <div class="form-row">
      <el-row>
        <el-tabs type="border-card" v-model="activeName">
          <el-tab-pane label="关爱问卷" name="careQuestionnaire"> <careQuestionnaire :type="type" :questionnaireId="returnVisitContent" :careStatus="careStatus" :customerCareId="customerCareId" ref="careQuestionnaire"/></el-tab-pane>
          <el-tab-pane label="关爱任务" name="caretask"><caretask :showChildren="showChildren" :employeeId="employeeId" :careTargetId="careTargetId" ref="careTask"/></el-tab-pane>
          <el-tab-pane label="关爱记录" name="careHistory"><careHistory :careTargetId="careTargetId" ref="careHistory"/></el-tab-pane>
        </el-tabs>
      </el-row>
    </div>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">取 消</el-button>
      <el-button v-if="type !== 'show'" @click="saveDialog" type="primary">关 爱</el-button>
    </div>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { formatdate } from '@/utils/index';
import { getCareBaseDateList } from '@/api/customerCare/visitRules/dissatisfaction';
import { getCareInfo, getPotentials, queryCustomerContactList, insertCareRecord } from '@/api/customerCare/saleVisit/salesVisit';
import careQuestionnaire from '../../tabs/careQuestionnaire.vue';
import caretask from '../../tabs/careTask.vue';
import careHistory from '../../tabs/careHistory.vue';

export default {
  name: 'SalesVisitDetail',
  mixins: [dictionary],
  components: {
    careQuestionnaire,
    caretask,
    careHistory
  },
  props: {
    billId: String,
    careTargetId: String,
    employeeId: String,
    type: String,
    returnVisitContent: String,
    customerCareId: String,
    recordVersion: String,
    requiredDate: String,
    showChildren: Boolean,
    careStatus: Number,
    customerBusinessId: String
  },
  data(){
    return {
      customerColumns: this.createCustoemrFormList(),
      contactsColumns: this.createContactsFormList(),
      contactsList: [],
      customerList: [],
      saveData: {},
      formList: this.createFormList(),
      activeName: 'careQuestionnaire'
    }
  },
  created() {
    this.init();
  },
  methods: {
    init(){
      getCareInfo(this.careTargetId).then(res => {
        if(res.resultCode == 200){
          this.formList.forEach(x => {
            if(x.fieldName=="careName"&&this.type=="add"){
              x.initialValue = res.data[x.fieldName];
            }else{
              if(res.data[x.fieldName]!=15921001&&x.fieldName != 'nextCareDate'){
                x.initialValue = res.data[x.fieldName];
              }
              if(x.fieldName === 'nextCareDate'&&x.initialValue&&x.initialValue!=''&&this.type!="add"){
                x.initialValue = formatdate(new Date(parseInt(x.initialValue)), 1);
              }
            }
          });
        }else{
          this.$message.error('查询关爱信息失败!');
        }
      });

      getCareBaseDateList({"baseDataType":1001}).then(res=>{
        if(res.resultCode == 200){
          this.formList.find(item=>item.fieldName==='basedataId').itemList = res.data.map(x => ({ value: x.baseDataId, text: x.baseDataName }));
        }else{
          this.$message.error('回去不满意原因失败!');
        }
      })

      getPotentials(this.billId).then(res => {
        if(res.resultCode == 200){
          let result = [];
          result.push(res.data);
          this.customerList = result;
        }else{
          this.$message.error('查询客户信息失败!');
        }
      });
      queryCustomerContactList({customerBusinessId:this.customerBusinessId}).then(res => {
        if(res.resultCode == 200){
          this.contactsList = res.data;
        }else{
          this.$message.error('查询联系人失败!');
        }
      });
    },
    createFormList(){
      return [
        {
          type: 'INPUT',
          label: '关爱名称',
          disabled: true,
          fieldName: 'careName'
        },
        {
          type: 'SELECT',
          label: '关爱方式',
          disabled: true,
          itemList: this.createDictList('1587'),
          initialValue: 15871003,
          fieldName: 'careWay',
          change:val=>{
            if(val==15871002||val==15871004){
              this.formList.find(item=>item.fieldName==='careContent').initialValue = '';
              this.formList.find(item=>item.fieldName==='careContent').disabled = true;
            }else{
              this.formList.find(item=>item.fieldName==='careContent').disabled = false;
            }
          }
        },
        {
          type: 'SELECT',
          label: '关爱状态',
          fieldName: 'careStatus',
          itemList: [{text:"继续关爱",value:15921002},{text:"成功关爱",value:15921003},{text:"失败关爱",value:15921004}],
          initialValue: 15921002,
          rules: [{ required: true, message: '请选择关爱状态', trigger: 'blur' }],
          change: val=>{
            this.careStatusChange(val);
          }
        },
        {
          type: 'DATE',
          label: '下次关爱日期',
          fieldName: 'nextCareDate',
          minDateTime: formatdate(new Date(),1),
          dateType: 'exactdate',
          initialValue: '',
          rules: []
        },
        {
          type: 'INPUT',
          label: '关爱内容',
          fieldName: 'careContent',
          maxlength: 100
        },
        {
          type: 'SELECT',
          label: '总体满意度',
          fieldName: 'satisfaction',
          disabled: true,
          rules: [],
          itemList: this.createDictList('1075'),
          change: val=>{
            debugger
            if(val==10751004||val==10751005){
              this.formList.find(item=>item.fieldName === "basedataId").rules = [{ required: true, message: '请选择不满意原因', trigger: 'blur' }];
              this.formList.find(item=>item.fieldName === "basedataId").disabled = false;
            }else{
              this.formList.find(item=>item.fieldName === "basedataId").initialValue = '';
              this.formList.find(item=>item.fieldName === "basedataId").rules = [];
              this.formList.find(item=>item.fieldName === "basedataId").disabled = true;
            }
          }
        },
        {
          type: 'SELECT',
          label: '不满意原因',
          fieldName: 'basedataId',
          itemList: [],
          rules: [],
          disabled: true
        },
        {
          type: 'SELECT',
          label: '失败原因',
          disabled: true,
          fieldName: 'careFailureReason',
          rules: [],
          itemList: this.createDictList('1594')
        }
      ]
    },
    createCustoemrFormList(){
      return [
        {
          title: '客户名称',
          dataIndex: 'customerName',
          filterType: 'input'
        },
        {
          title: '销售顾问',
          dataIndex: 'consultant',
          filterType: 'input'
        },
        {
          title: 'VIN',
          dataIndex: 'salesVin',
          filterType: 'input',
          width: 150
        },
        {
          title: '品牌',
          dataIndex: 'brandName',
          filterType: 'input'
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          filterType: 'input'
        },
        {
          title: '出库日期',
          dataIndex: 'stockInOutDate',
          filterType: 'input',
          render: props => {
            if(props.row.stockInOutDate&&props.row.stockInOutDate!=''){
              return <div>{formatdate(new Date(parseInt(props.row.stockInOutDate)), 1)}</div>;
            }
          }
        },
        {
          title: '性别',
          dataIndex: 'gender',
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.gender, '1002')}</div>;
          }
        },
        {
          title: '地址',
          dataIndex: 'address',
          filterType: 'input'
        },
        {
          title: '联系人',
          dataIndex: 'customerName2',
          filterType: 'input',
          render: props => {
            return <div>{props.row.customerName}</div>;
          }
        },
        {
          title: '联系人手机',
          dataIndex: 'mobilePhone',
          filterType: 'input'
        },
        {
          title: '联系人电话',
          dataIndex: 'phone',
          filterType: 'input'
        },
        {
          title: '省份',
          dataIndex: 'province',
          filterType: 'input'
        },
        {
          title: '城市',
          dataIndex: 'city',
          filterType: 'input'
        },
        {
          title: '区县',
          dataIndex: 'district',
          filterType: 'input'
        },
        {
          title: 'Email',
          dataIndex: 'eMail',
          filterType: 'input'
        },
        {
          title: '客户类型',
          dataIndex: 'customerType',
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.customerType, '1523')}</div>;
          }
        },
        {
          title: '婚姻状况',
          dataIndex: 'maritalStatus',
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.maritalStatus, '7028')}</div>;
          }
        },
        {
          title: '教育水平',
          dataIndex: 'educationalLevel',
          filterType: 'input'
        },
        {
          title: '职业',
          dataIndex: 'postName',
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.postName, '7031')}</div>;
          }
        },
        {
          title: '开票日期',
          dataIndex: 'invoiceDate',
          filterType: 'input',
          render: props => {
            if(props.row.invoiceDate&&props.row.invoiceDate!=''){
              return <div>{formatdate(new Date(parseInt(props.row.invoiceDate)), 1)}</div>;
            }
          }
        },
        {
          title: '客户来源',
          dataIndex: 'customerFrom',
          filterType: 'input'
        },
        {
          title: '备注',
          dataIndex: 'remark',
          filterType: 'input'
        }
      ]
    },
    createContactsFormList(){
      return [
        {
          title: '序号',
          dataIndex: 'index',
          align: 'center',
          width: 70,
          fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '主要联系人',
          dataIndex: 'isMain',
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.isMain, '1004')}</div>;
          }
        },
        {
          title: '联系人',
          dataIndex: 'contactName',
          filterType: 'input'
        },
        {
          title: '联系手机',
          dataIndex: 'contactorPhone',
          filterType: 'input'
        },
        {
          title: '联系固话',
          dataIndex: 'contactorMobile',
          filterType: 'input'
        },
        {
          title: '联系人类型',
          dataIndex: 'contactType',
          filterType: 'select',
          render: props => {
            return <div>{this.createDictText(props.row.contactType, '7034')}</div>;
          }
        },
        {
          title: '关系',
          dataIndex: 'contactRelation',
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.contactRelation, '1534')}</div>;
          }
        },
        {
          title: '联系方式',
          dataIndex: 'contactMethod',
          filterType: 'input'
        },
        {
          title: '性别',
          dataIndex: 'gender',
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.gender, '1002')}</div>;
          }
        },
        {
          title: '联系时间',
          dataIndex: 'contactTime	',
          filterType: 'input'
        },
        {
          title: '备注',
          dataIndex: 'contactRemark',
          filterType: 'input'
        }
      ]
    },
    careStatusChange(val){
      if(val == 15921004){
        this.formList.find(item=>item.fieldName === "careFailureReason").rules = [{ required: true, message: '请选择失败原因', trigger: 'blur' }];
        this.formList.find(item=>item.fieldName === "careFailureReason").disabled = false;
      }else{
        this.formList.find(item=>item.fieldName === "careFailureReason").initialValue = '';
        this.formList.find(item=>item.fieldName === "careFailureReason").rules = [];
        this.formList.find(item=>item.fieldName === "careFailureReason").disabled = true;
      };
      if(val == 15921003){
        this.formList.find(item=>item.fieldName === "satisfaction").rules = [{ required: true, message: '请选择总体满意度', trigger: 'blur' }];
        this.formList.find(item=>item.fieldName === "satisfaction").disabled = false;
      }else{
        this.formList.find(item=>item.fieldName === "satisfaction").initialValue = '';
        this.formList.find(item=>item.fieldName === "basedataId").initialValue = '';
        this.formList.find(item=>item.fieldName === "satisfaction").rules = [];
        this.formList.find(item=>item.fieldName === "basedataId").rules = [];
        this.formList.find(item=>item.fieldName === "satisfaction").disabled = true;
        this.formList.find(item=>item.fieldName === "basedataId").disabled = true;
      };
      if(val == 15921002){
        this.formList.find(item=>item.fieldName === "nextCareDate").rules = [{ required: true, message: '请选择下次关爱日期', trigger: 'blur' }];
        this.formList.find(item=>item.fieldName === "nextCareDate").disabled = false;
      }else{
        this.formList.find(item=>item.fieldName === "nextCareDate").initialValue = '';
        this.formList.find(item=>item.fieldName === "nextCareDate").rules = [];
        this.formList.find(item=>item.fieldName === "nextCareDate").disabled = true;
      }
    },
    addContacts() {
      let row = {
        index:this.contactsList.length
      }
      this.contactsList.push(row);
    },
    delContacts(row) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.contactsList.splice(row.$index, 1);
      });
    },
    closeDialog(param) {
      this.$emit('close', false, param);
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    saveDialog(){
      this.$refs.formPanel.SUBMIT_FORM();
      this.saveData.questionnaireId = this.returnVisitContent;
      this.saveData.careTargetId = this.careTargetId;
      this.saveData.recordVersion = this.recordVersion;
      if(this.saveData.nextCareDate&&this.saveData.nextCareDate!=''){
        this.saveData.nextCareDate = this.saveData.nextCareDate+" 00:00:00";
      }

      var questionnaireDom = document.getElementById("questionnaire");
      if(questionnaireDom){
        let questionnaireList = [];
        let questionnaireChildren = questionnaireDom.children;
        let validate = 0;
        for(let i=0;i<questionnaireChildren.length;i++){
          let dom = questionnaireChildren[i];
          let questionnaire = {};
          questionnaire.questionnaireId = this.returnVisitContent;
          if(dom.getAttribute("questionType")!=15711003){
            questionnaire.answerGroupId = dom.getAttribute("answerGroupId");
          }
          questionnaire.answerQuestionnaireId = dom.getAttribute("answerQuestionnaireId");
          questionnaire.isMustFilled = dom.getAttribute("isMustFilled");
          questionnaire.questionContent = dom.getAttribute("questionContent");
          questionnaire.questionId = dom.getAttribute("id");
          questionnaire.questionName = dom.getAttribute("questionName");
          questionnaire.questionType = dom.getAttribute("questionType");
          if(dom.getAttribute("questionType")==15711003){
            let textareaVal = dom.children[0].getElementsByTagName('textarea')[0].value;
            if(this.saveData.satisfaction == 10751004 || this.saveData.satisfaction == 10751005){
              if(dom.getAttribute("isMustFilled")==10041001&&(!textareaVal||textareaVal=="")){
                validate++;
              }
            }
            questionnaire.value = textareaVal;
          }else{
            let answerList = [];
            let answerIds = "";
            let answerChildren = dom.children[0].getElementsByTagName("input");
            for(let i=0;i<answerChildren.length;i++){
              let answer = {};
              let answerDom = answerChildren[i];
              answer.answer = answerDom.getAttribute("answer");
              answer.answerId = answerDom.getAttribute("answerId");
              answer.answerQuestionnaireId = answerDom.getAttribute("answerQuestionnaireId");
              answer.answerSort = answerDom.getAttribute("answerSort");
              answer.answerUsedId = answerDom.getAttribute("answerUsedId");
              if(answerDom.checked){
                answer.isChecked = 10041001;
                answerIds += answerDom.getAttribute("answerId")+",";
              }else{
                answer.isChecked = 10041002;
              }
              answerList.push(answer);
              questionnaire.answerList = answerList;
            }
            if(answerIds!=""){
              questionnaire.value = answerIds.substring(0,answerIds.length-1);
            }else{
              if(this.saveData.satisfaction == 10751004 || this.saveData.satisfaction == 10751005){
                if(dom.getAttribute("isMustFilled")==10041001){
                  validate++;
                }
              }
            }
          }
          questionnaireList.push(questionnaire);
        }
        if(validate>0){
          this.$message.error('请填写问卷！');
          return;
        }
        this.saveData.questionInfoVOList = questionnaireList;
      }
      insertCareRecord(this.saveData).then(res=>{
        if(res.resultCode == 200){
          this.closeDialog('refresh');
        }else{
          this.$message.error('保存关爱记录失败');
        }
      })
    }
  }
}
</script>
